package com.qeeyou.apps.android.craftsman.activity.publish;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.qeeyou.apps.android.craftsman.R;
import com.qeeyou.apps.android.craftsman.adapter.SelectImageGridAdapter;
import com.qeeyou.apps.android.craftsman.common.Contants;
import com.qeeyou.apps.android.craftsman.po.CommonInfo;
import com.qeeyou.apps.android.craftsman.po.InstallMethodInfo;
import com.qeeyou.apps.android.craftsman.po.InstallTypeInfo;
import com.qeeyou.apps.android.craftsman.po.InstallShopInfo;
import com.qeeyou.apps.android.craftsman.po.UserAddressInfo;
import com.qeeyou.apps.android.craftsman.po_wrap.InstallMaterialWrapInfo;
import com.qeeyou.apps.android.craftsman.service.AppService;
import com.qeeyou.apps.android.craftsman.utils.GifSizeFilter;
import com.qeeyou.apps.android.craftsman.view.CustomLoadingDialog;
import com.qeeyou.apps.android.craftsman.view.NoScrollGridView;
import com.qeeyou.apps.android.craftsman.view.wheelview.Common;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;
import com.zhihu.matisse.filter.Filter;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * Created by lzx on 25/01/2018.
 */

public class PublishStep2Activity extends Activity implements EasyPermissions.PermissionCallbacks {

    private static final String TAG = PublishStep2Activity.class.getSimpleName();

    private static final int RC_CAMERA_PERM = 123;

    private Context mContext;

    private ImageView mBtnBack;
    private NoScrollGridView mGvImage;
    private EditText mEtComment;
    private LinearLayout mBtnPublish;

    private SelectImageGridAdapter mGridAdapter;
    private List<String> mImagePathList = new ArrayList<String>();

    private CustomLoadingDialog mLoadingDialog;

    private InstallTypeInfo mInstallTypeInfo;
    private UserAddressInfo mUserAddressInfo;
    private InstallShopInfo mInstallShopInfo;
    private InstallMethodInfo mInstallMethodInfo;
    private InstallMaterialWrapInfo mInstallMaterialInfo;
    private String mInstallTime;
    private String mWorkingDay;
    private String mInstallNum;
    private String mInstallLength;
    private String mInstallPrice;
    private String mInstallUnitPrice;                                    //安装单价

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_publish_step_2);

        mContext = this;

        Intent intent = getIntent();
        if(intent != null) {
            mUserAddressInfo = (UserAddressInfo) intent.getParcelableExtra(Contants.Extra.EXTRA_ADDRESS_INFO);
            mInstallTime = intent.getStringExtra(Contants.Extra.EXTRA_INSTALL_TIME);
            mWorkingDay = intent.getStringExtra(Contants.Extra.EXTRA_WORKING_DAY);
            mInstallNum = intent.getStringExtra(Contants.Extra.EXTRA_INSTALL_NUM);
            mInstallTypeInfo = (InstallTypeInfo) intent.getSerializableExtra(Contants.Extra.EXTRA_INSTALL_TYPE);
            mInstallShopInfo = (InstallShopInfo) intent.getSerializableExtra(Contants.Extra.EXTRA_INSTALL_SHOP);
            mInstallMethodInfo = (InstallMethodInfo) intent.getSerializableExtra(Contants.Extra.EXTRA_INSTALL_METHOD);
            mInstallMaterialInfo = (InstallMaterialWrapInfo)intent.getSerializableExtra(Contants.Extra.EXTRA_INSTALL_MATERIAL);
            mInstallLength = intent.getStringExtra(Contants.Extra.EXTRA_INSTALL_LENGTH);
            mInstallPrice = intent.getStringExtra(Contants.Extra.EXTRA_INSTALL_PRICE);
            mInstallUnitPrice = intent.getStringExtra(Contants.Extra.EXTRA_INSTALL_UNIT_PRICE);
        }

        setView();
        setEvent();
    }

    private void setView() {
        mBtnBack = (ImageView) this.findViewById(R.id.btnBack4PublishStep2);
        mGvImage = (NoScrollGridView) findViewById(R.id.nsgvImage4PublishStep2);
        mEtComment = (EditText) findViewById(R.id.etComment4PublishStep2);
        mBtnPublish = (LinearLayout) findViewById(R.id.btnPublish4PublishStep2);

        mGridAdapter = new SelectImageGridAdapter(this, mImagePathList, 4);
        mGvImage.setAdapter(mGridAdapter);
    }

    private void setEvent() {
        mBtnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        mGridAdapter.setOnItemClickListener(new SelectImageGridAdapter.OnItemClickListener() {
            @Override
            public void onItemImageClick(int position) {
                if (position == mImagePathList.size()) {
                    cameraTask();
                } else {
                    startActivityForResult(new Intent(mContext, ImagePreviewActivity.class)
                                    .putExtra(Contants.Extra.EXTRA_IMAGE_ID, position)
                                    .putExtra(Contants.Extra.EXTRA_IMAGE_LIST, (Serializable) mImagePathList)
                                    .putExtra(Contants.Extra.EXTRA_IMAGE_PREVIEW_IS_SHOW_DELETE, true)
                            , Contants.RequestCode.REQUEST_IMAGE_PREVIEW);
                }
            }

            @Override
            public void onItemCancelClick(int position) {
                mImagePathList.remove(position);
                mGridAdapter.update(mImagePathList);
            }
        });

        mBtnPublish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //TODO -- 提交信息
                String remarkText = mEtComment.getText().toString();
                remarkText = remarkText != null ? remarkText : "";
                String shopId = mInstallShopInfo.getShopid();
                String materialId = "";
                if(mInstallMaterialInfo != null) {
                    materialId = mInstallMaterialInfo.getMaterialInfo().getId();
                }
                String serviceTypeId = "";
                String serviceTypeName = "";
                if(mInstallTypeInfo != null) {
                    serviceTypeId = mInstallTypeInfo.getTypeid();
                    serviceTypeName = mInstallTypeInfo.getTypename();
                }
                if(serviceTypeName != null && serviceTypeName.trim().equalsIgnoreCase("高级")) {
                    if(materialId.trim().equalsIgnoreCase("")) {
                        materialId = "no_use";
                    }
                }
                String serviceMethodId = "";
                if(mInstallMethodInfo != null) {
                    serviceMethodId = mInstallMethodInfo.getMethodid();
                }
                String serviceTime = mInstallTime;
                String addressId = mUserAddressInfo.getAddressid();
                if(mInstallNum == null || mInstallNum.trim().equalsIgnoreCase("")) {
                    mInstallNum = mInstallLength;
                }
                String orderSum = mInstallNum;
                String memo = remarkText;
                String orderTime = "";
                if(mWorkingDay != null) {
                    orderTime = mWorkingDay;
                }
                String orderPrice = "";
                if(mInstallPrice != null) {
                    orderPrice = mInstallPrice;
                }
                String length = "";
                if(mInstallLength != null) {
                    length = mInstallLength;
                }
                String unitPrice = "";
                if(mInstallUnitPrice != null) {
                    unitPrice = mInstallUnitPrice;
                }
                String[] params = new String[] { shopId, materialId, serviceTypeId, serviceMethodId,
                        serviceTime, addressId, orderSum, memo, orderTime, orderPrice, length, unitPrice};
                new UserOrderAction().execute(params);
            }
        });
    }

    @AfterPermissionGranted(RC_CAMERA_PERM)
    public void cameraTask() {
        if (EasyPermissions.hasPermissions(this,
                new String[]{Manifest.permission.CAMERA,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE
                        })) {
            // Have permission, do the thing!
            Matisse.from((Activity) mContext)
                    .choose(MimeType.ofAll(), false)
                    .countable(true)
                    .capture(true)
                    .captureStrategy(new CaptureStrategy(true, Contants.Client.FILE_PROVIDER))
                    .maxSelectable(4 - mImagePathList.size())
                    .addFilter(new GifSizeFilter(320, 320, 5 * Filter.K * Filter.K))
                    .gridExpectedSize(
                            getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
                    .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
                    .thumbnailScale(0.85f)
                    .imageEngine(new GlideEngine())
                    .forResult(Contants.RequestCode.REQUEST_TAKE_IMAGE_FROM_ALBUM);
        } else {
            // Ask for one permission
            EasyPermissions.requestPermissions(
                    this,
                    getString(R.string.permission_request_denied),
                    RC_CAMERA_PERM,
                    new String[]{
                            Manifest.permission.CAMERA,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE});
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        // EasyPermissions handles the request result.
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        Log.d(TAG, "onPermissionsGranted:" + requestCode + ":" + perms.size());
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        Log.d(TAG, "onPermissionsDenied:" + requestCode + ":" + perms.size());

        // (Optional) Check whether the user denied any permissions and checked "NEVER ASK AGAIN."
        // This will display a dialog directing them to enable the permission in app settings.
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this).build().show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case Contants.RequestCode.REQUEST_TAKE_IMAGE_FROM_ALBUM:
                if (resultCode == RESULT_OK) {
                    mImagePathList.addAll(Matisse.obtainPathResult(data));
                    mGridAdapter.update(mImagePathList);
                }
                break;
            case Contants.RequestCode.REQUEST_IMAGE_PREVIEW:
                if (resultCode == RESULT_OK) {
                    mImagePathList = (List<String>) data.getSerializableExtra(Contants.Extra.EXTRA_IMAGE_LIST);
                    mGridAdapter.update(mImagePathList);
                }
                break;
        }
    }

    //用户下单
    class UserOrderAction extends AsyncTask<String, Void, CommonInfo> {
        public UserOrderAction() {
            super();
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            if (mLoadingDialog == null) {
                mLoadingDialog = new CustomLoadingDialog(PublishStep2Activity.this);
            }
            mLoadingDialog.setMessage("正在提交订单...");
            mLoadingDialog.show();
        }

        @Override
        protected CommonInfo doInBackground(String... params) {
            String shopId = params[0];
            String materialId = params[1];
            String serviceTypeId = params[2];
            String serviceMethodId = params[3];
            String serviceTime = params[4];
            String addressId = params[5];
            String orderSum = params[6];
            String memo = params[7];
            String orderTime = params[8];
            String orderPrice = params[9];
            String length = params[10];
            String unitPrice = params[11];
            Map<String, String> paramMap = new HashMap<String, String>();
            paramMap.put("imgname", "imgname");
            paramMap.put("shopid", shopId);
            paramMap.put("servicetime", serviceTime);
            paramMap.put("addressid", addressId);
            paramMap.put("ordersum", orderSum);
            if(materialId != null && !materialId.trim().equalsIgnoreCase("")) {
                if(materialId.trim().equalsIgnoreCase("no_use")) {
                    //高级订单
                    if(paramMap.containsKey("materialid")) {
                        paramMap.remove("materialid");
                    }
                    paramMap.put("unitprice", unitPrice);
                } else {
                    paramMap.put("materialid", materialId);
                }
            } else {
                paramMap.put("materialid", "");
            }
            paramMap.put("servicetypeid", serviceTypeId);
            if(serviceMethodId != null && !serviceMethodId.trim().equalsIgnoreCase("")) {
                paramMap.put("servicemethodid", serviceMethodId);
            } else {
                paramMap.put("servicemethodid", "");
            }
            if(memo != null && !memo.trim().equalsIgnoreCase("")) {
                paramMap.put("memo", memo);
            } else {
                paramMap.put("memo", "");
            }
            if(orderTime != null && !orderTime.trim().equalsIgnoreCase("")) {
                paramMap.put("ordertime", orderTime);
            } else {
                paramMap.put("ordertime", "");
                if(!paramMap.containsKey("materialid")) {
                    paramMap.remove("ordertime");
                }
            }
            if(orderPrice != null && !orderPrice.trim().equalsIgnoreCase("")) {
                paramMap.put("orderprice", orderPrice);
            } else {
                paramMap.put("orderprice", "");
            }
            if(mImagePathList != null && !mImagePathList.isEmpty()) {
                //上传图片
                List<String> imagePathList = AppService.getInstance().uploadImages(mImagePathList);
                if(imagePathList != null && !imagePathList.isEmpty()) {
                    String imagePaths = "";
                    for(int i = 0, n = imagePathList.size(); i < n; i++) {
                        imagePaths = imagePaths + ("," + imagePathList.get(i));
                    }
                    imagePaths = imagePaths.substring(1);
                    paramMap.put("imgname", imagePaths);
                } else {
                    paramMap.put("imgname", "");
                }
            } else {
                paramMap.put("imgname", "");
            }
            CommonInfo resultInfo = AppService.getInstance().userOrder(paramMap);
            return resultInfo;
        }

        @Override
        protected void onPostExecute(CommonInfo resultInfo) {
            super.onPostExecute(resultInfo);
            if (mLoadingDialog != null) {
                mLoadingDialog.dismiss();
                mLoadingDialog = null;
            }
            if (resultInfo != null && resultInfo.getStatus().equalsIgnoreCase("1")) {
                Toast.makeText(PublishStep2Activity.this, "下单成功", Toast.LENGTH_SHORT).show();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Intent intent = new Intent(PublishStep2Activity.this, PayActivity.class);
                        if(mInstallPrice != null) {
                            intent.putExtra(Contants.Extra.EXTRA_INSTALL_PRICE, mInstallPrice);
                        }
                        PublishStep2Activity.this.startActivity(intent);
                        PublishStep2Activity.this.finish();
                    }
                }, 1000);
            } else {
                Toast.makeText(PublishStep2Activity.this, "下单失败", Toast.LENGTH_SHORT).show();
            }
        }
    }
}
